import { LoginData, login as userLogin } from '@/api/user';
import { useTabBarStore } from '@/store';
import { clearToken, setToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { defineStore } from 'pinia';
import useAppStore from '../app';
import { UserState } from './types';
let user_: any;
const useUserStore = defineStore('user', {
  state: (): any => ({
    id: undefined,
    name: undefined,
    avatar: undefined,
    username: undefined,
    nickname: undefined,
    birthday: undefined,
    gender: undefined,
    intr: undefined,
    squad_id: undefined,
    token: undefined,
    createtime: undefined,
    expiretime: undefined,
    expires_in: undefined,
    menu: [],
    role: '',
    default_path: undefined,
    default_name: undefined,
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
      localStorage.removeItem('giftbox-userinfo');
    },

    // Get user's information
    async info() {
      const res = user_;

      this.setInfo(res.data);
    },

    // Login
    async login(loginForm: LoginData, callback: Function) {
      try {
        const res = await userLogin(loginForm);
        console.error(res);
        setToken(res.data.token);
        user_ = res;
        callback && callback(res.data);
        // this.setInfo(res.data);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
      useTabBarStore().resetTabList();
      localStorage.clear();
      sessionStorage.clear();
      function clearAllCookie() {
        var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
        if (keys) {
          for (var i = keys.length; i--; )
            document.cookie =
              keys[i] + '=0;expires=' + new Date(0).toUTCString();
        }
      }
      clearAllCookie();
    },
    // Logout
    async logout() {
      try {
        // await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
  persist: {
    key: 'giftbox-userinfo',
  },
});

export default useUserStore;
